# import pygame
# import random
# from pykakasi import kakasi  # 需要 pip install pykakasi

# # 初始化假名转换器
# kakasi_converter = kakasi()
# kakasi_converter.setMode("H", "a")  # 平假名转罗马字
# kakasi_converter.setMode("K", "a")  # 片假名转罗马字
# kana_to_roma = kakasi_converter.getConverter()

# def to_roma(text):
#     """将假名转换为全小写罗马字"""
#     return kana_to_roma.do(text).lower()

# # 初始化 Pygame
# pygame.init()

# # 屏幕设置
# SCREEN_WIDTH = 800
# SCREEN_HEIGHT = 600
# screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
# pygame.display.set_caption("日语打字大战 - pykakasi版")

# # 颜色常量
# BLACK = (0, 0, 0)
# WHITE = (255, 255, 255)
# RED = (255, 0, 0)
# GREEN = (0, 255, 0)

# # 加载字体（推荐使用 Noto Sans Japanese）
# try:
#     font = pygame.font.Font("D:/pythonProgramms/exam/japGame/SourceHanSans-Normal.otf", 24)
# except:
#     font = pygame.font.SysFont("msmincho", 24)  # Windows 日文字体

# # 玩家飞船类
# class Player(pygame.sprite.Sprite):
#     def __init__(self):
#         super().__init__()
#         self.image = pygame.Surface((40, 20))
#         self.image.fill(GREEN)
#         self.rect = self.image.get_rect(center=(SCREEN_WIDTH//2, SCREEN_HEIGHT-30))

# # 敌人类（使用 pykakasi 转换）
# class Enemy(pygame.sprite.Sprite):
#     def __init__(self, kana):
#         super().__init__()
#         self.kana = kana
#         self.roma = to_roma(kana)  # 使用 pykakasi 转换
#         self.image = font.render(kana, True, WHITE)
#         self.rect = self.image.get_rect(
#             center=(random.randint(50, SCREEN_WIDTH-50), -20)
#         )
#         self.speed = random.randint(1, 3)
    
#     def update(self):
#         self.rect.y += self.speed
#         if self.rect.top > SCREEN_HEIGHT:
#             self.kill()

# # 子弹类（保持不变）
# class Bullet(pygame.sprite.Sprite):
#     def __init__(self, target, start_pos):
#         super().__init__()
#         self.target = target
#         self.image = pygame.Surface((5, 10))
#         self.image.fill(RED)
#         self.rect = self.image.get_rect(center=start_pos)
#         self.speed = 8
    
#     def update(self):
#         if self.target:
#             dx = self.target.rect.centerx - self.rect.centerx
#             dy = self.target.rect.centery - self.rect.centery
#             distance = max(1, (dx**2 + dy**2)**0.5)
#             self.rect.x += dx / distance * self.speed
#             self.rect.y += dy / distance * self.speed

# # 游戏初始化
# all_sprites = pygame.sprite.Group()
# enemies = pygame.sprite.Group()
# bullets = pygame.sprite.Group()
# player = Player()
# all_sprites.add(player)

# score = 0
# lives = 3
# input_buffer = ""
# # 包含平假名和片假名的列表
# kana_list = [
#     'あ', 'い', 'う', 'え', 'お',
#     'か', 'き', 'く', 'け', 'こ',
#     'ア', 'イ', 'ウ', 'エ', 'オ',
#     'カ', 'キ', 'ク', 'ケ', 'コ'
# ]

# # 敌人生成计时器
# ENEMY_EVENT = pygame.USEREVENT + 1
# pygame.time.set_timer(ENEMY_EVENT, 5000)

# running = True
# clock = pygame.time.Clock()

# while running:
#     screen.fill(BLACK)
    
#     for event in pygame.event.get():
#         if event.type == pygame.QUIT:
#             running = False
#         elif event.type == ENEMY_EVENT:
#             new_enemy = Enemy(random.choice(kana_list))
#             all_sprites.add(new_enemy)
#             enemies.add(new_enemy)
#         elif event.type == pygame.KEYDOWN:
#             if event.key == pygame.K_SPACE:
#                 # 检查输入是否匹配敌人
#                 for enemy in enemies:
#                     if input_buffer == enemy.roma:
#                         bullet = Bullet(enemy, player.rect.center)
#                         all_sprites.add(bullet)
#                         bullets.add(bullet)
#                         break
#                 input_buffer = ""
#             elif event.key == pygame.K_BACKSPACE:
#                 input_buffer = input_buffer[:-1]
#             else:
#                 char = event.unicode.lower()
#                 if char.isalpha():
#                     input_buffer += char
    
#     # 更新游戏对象
#     all_sprites.update()
    
#     # 子弹命中检测
#     for bullet in bullets:
#         if bullet.target and pygame.sprite.collide_rect(bullet, bullet.target):
#             bullet.target.kill()
#             bullet.kill()
#             score += 10
    
#     # 敌人到达底部检测
#     for enemy in enemies:
#         if enemy.rect.top > SCREEN_HEIGHT:
#             lives -= 1
#             if lives <= 0:
#                 running = False
    
#     # 渲染画面
#     all_sprites.draw(screen)
    
#     # 显示游戏信息
#     info_y = 10
#     screen.blit(font.render(f"スコア: {score}", True, WHITE), (10, info_y))
#     screen.blit(font.render(f"ライフ: {lives}", True, WHITE), (SCREEN_WIDTH-150, info_y))
#     screen.blit(font.render(f"入力: {input_buffer}", True, WHITE), (SCREEN_WIDTH//2-60, info_y))
    
#     pygame.display.flip()
#     clock.tick(60)

# pygame.quit()首个成功版本

import pygame
import random
import os
from pykakasi import kakasi

# 初始化假名转换器
kakasi_converter = kakasi()
kakasi_converter.setMode("H", "a")  # 平假名转罗马字
kakasi_converter.setMode("K", "a")  # 片假名转罗马字
kana_to_roma = kakasi_converter.getConverter()

def to_roma(text):
    """将假名转换为全小写罗马字"""
    return kana_to_roma.do(text).lower()

# 初始化 Pygame
pygame.init()
pygame.mixer.init()  # 初始化音频模块

# 屏幕设置
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("日语打字大战 - 完整版")

# 颜色常量
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)

# 加载资源
try:
    # 获取当前文件目录
    current_dir = os.path.dirname(os.path.abspath(__file__))
    
    # 加载字体
    font_path = os.path.join(current_dir, "SourceHanSans-Normal.otf")
    font = pygame.font.Font(font_path, 24)
    
    # 加载音效
    shoot_sound = pygame.mixer.Sound(os.path.join(current_dir, "shoot.mp3"))
    hit_sound = pygame.mixer.Sound(os.path.join(current_dir, "hit.mp3"))
    enemy_pass_sound = pygame.mixer.Sound(os.path.join(current_dir, "warning.mp3"))
    game_over_sound = pygame.mixer.Sound(os.path.join(current_dir, "gameover.mp3"))
    
    # 背景音乐
    pygame.mixer.music.load(os.path.join(current_dir, "bgm.mp3"))
    pygame.mixer.music.set_volume(0.3)  # 背景音乐音量
except Exception as e:
    print("资源加载错误:", e)
    font = pygame.font.SysFont("msmincho", 24)
    shoot_sound = hit_sound = enemy_pass_sound = game_over_sound = None

# 玩家飞船类
class Player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.Surface((40, 20))
        self.image.fill(GREEN)
        self.rect = self.image.get_rect(center=(SCREEN_WIDTH//2, SCREEN_HEIGHT-30))

# 敌人类
class Enemy(pygame.sprite.Sprite):
    def __init__(self, kana):
        super().__init__()
        self.kana = kana
        self.roma = to_roma(kana)
        self.image = font.render(kana, True, WHITE)
        self.rect = self.image.get_rect(
            center=(random.randint(50, SCREEN_WIDTH-50), -20)
        )
        self.speed = random.randint(1, 3)
    
    def update(self):
        self.rect.y += self.speed

# 子弹类
class Bullet(pygame.sprite.Sprite):
    def __init__(self, target, start_pos):
        super().__init__()
        self.target = target
        self.image = pygame.Surface((5, 10))
        self.image.fill(RED)
        self.rect = self.image.get_rect(center=start_pos)
        self.speed = 8
    
    def update(self):
        if self.target:
            dx = self.target.rect.centerx - self.rect.centerx
            dy = self.target.rect.centery - self.rect.centery
            distance = max(1, (dx**2 + dy**2)**0.5)
            self.rect.x += dx / distance * self.speed
            self.rect.y += dy / distance * self.speed

# 游戏初始化
all_sprites = pygame.sprite.Group()
enemies = pygame.sprite.Group()
bullets = pygame.sprite.Group()
player = Player()
all_sprites.add(player)

score = 0
lives = 3
input_buffer = ""
kana_list = [
    'あ', 'い', 'う', 'え', 'お',
    'か', 'き', 'く', 'け', 'こ',
    'ア', 'イ', 'ウ', 'エ', 'オ',
    'カ', 'キ', 'ク', 'ケ', 'コ'
]

# 敌人生成计时器
ENEMY_EVENT = pygame.USEREVENT + 1
pygame.time.set_timer(ENEMY_EVENT, 1500)  # 调整为1.5秒生成一个敌人

# 播放背景音乐
pygame.mixer.music.play(-1)

running = True
clock = pygame.time.Clock()

while running:
    screen.fill(BLACK)
    
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == ENEMY_EVENT:
            new_enemy = Enemy(random.choice(kana_list))
            all_sprites.add(new_enemy)
            enemies.add(new_enemy)
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                # 检查输入匹配
                for enemy in enemies:
                    if input_buffer == enemy.roma:
                        bullet = Bullet(enemy, player.rect.center)
                        all_sprites.add(bullet)
                        bullets.add(bullet)
                        if shoot_sound: shoot_sound.play()
                        break
                input_buffer = ""
            elif event.key == pygame.K_BACKSPACE:
                input_buffer = input_buffer[:-1]
            else:
                char = event.unicode.lower()
                if char.isalpha():
                    input_buffer += char
    
    # 更新游戏对象
    all_sprites.update()
    
    # 子弹命中检测
    for bullet in bullets:
        if bullet.target and pygame.sprite.collide_rect(bullet, bullet.target):
            bullet.target.kill()
            bullet.kill()
            score += 10
            if hit_sound: hit_sound.play()
    
    # 敌人触底检测
    for enemy in enemies:
        if enemy.rect.top > SCREEN_HEIGHT:
            lives -= 1
            enemy.kill()
            if enemy_pass_sound: enemy_pass_sound.play()
            if lives <= 0:
                if game_over_sound: game_over_sound.play()
                running = False
    
    # 渲染画面
    all_sprites.draw(screen)
    
    # 显示游戏信息
    info_y = 10
    screen.blit(font.render(f"スコア: {score}", True, WHITE), (10, info_y))
    screen.blit(font.render(f"ライフ: {lives}", True, WHITE), (SCREEN_WIDTH-150, info_y))
    screen.blit(font.render(f"入力: {input_buffer}", True, WHITE), (SCREEN_WIDTH//2-60, info_y))
    
    pygame.display.flip()
    clock.tick(60)

pygame.mixer.music.stop()
pygame.quit()